<template>
  <div class="h-[12px]"></div>
  <div class="detail-style" id="scrollContainer" @scroll="handleScroll">
    <div id="top"></div>
    <Flow ref="FlowRef"></Flow>
    <div
      class="flex"
      :class="handleType != 'view' ? 'pb-42' : 'pb-30'"
      ref="scrollContainer"
    >
      <div class="flex-1" style="width: 80%">
        <el-card class="box-card mt-2" shadow="never">
          <div id="spuInfo" class="flex justify-between items-center">
            <div class="header-title">SPU信息</div>
            <div v-if="permission_spu_info">
              <el-button type="primary" @click="handleRegionSave('goods_spu')"
                >保存SPU信息</el-button
              >
            </div>
          </div>
          <SpuInfo
            ref="spuInfoRef"
            v-model="form"
            @initsku="initsku"
            @sync="syncName"
          ></SpuInfo>
        </el-card>

        <el-card class="box-card mt-2 mb-[10px]" shadow="never">
          <div id="multiattribute" class="header-title">多属性设置</div>
          <MultiAttribute
            ref="multiAttributeRef"
            v-model="form"
            :spu="form.spu"
            @change="changeAttribute"
            :permission_all="permission_all"
          >
            <template #handle="{ row }">
              <el-button
                v-if="permission_multiattribute_info && row.id"
                type="primary"
                link
                @click="
                  handleRegionSave(
                    'goods_sku_attr',
                    row,
                    '是否保存该条SKU的属性信息，点击确认后对改SKU属性信息执行保存，请知悉。'
                  )
                "
                >保存SKU属性</el-button
              >
            </template>
          </MultiAttribute>
        </el-card>

        <div id="SKUOffsetTop"></div>
        <el-affix :offset="95">
          <el-tabs
            v-model="activeName"
            type="card"
            class="px-2 pt-2 bg-[var(--base-dialog-bg-color)] border-b border-solid border-[#e4e7ed]"
            @tab-click="handleTag"
          >
            <el-tab-pane
              v-for="(item, index) in goods_sku_list"
              :key="index"
              :label="item.sku"
              :name="item.sku"
            >
              <template #label>
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  :content="item.sku_cn_title"
                  placement="top-start"
                >
                  {{ item.sku || item.custom_sku }}
                </el-tooltip>
                <span v-if="item.sales_status == 4" class="base-red-color"
                  >({{ item.sales_status_text }})</span
                >
              </template>
            </el-tab-pane>
          </el-tabs>
        </el-affix>
        <el-card class="box-card card-affix" shadow="never" v-if="form.goods_sku?.length">
          <div class="flex justify-between items-center h-[44px]">
            <div id="SKUMaintain" class="font-bold">SKU维护</div>
            <div class="flex">
              <el-button
                v-if="handleType != 'view' && form.goods_sku.length > 1"
                @click="copySKUFun('all')"
                :disabled="permission_all"
                >复制SKU信息</el-button
              >
            </div>
          </div>
          <div class="card-affix-tab" v-if="current_sku">
            <el-card class="box-card card-content-line" shadow="never">
              <div id="SKUInfo" class="SKUInfo flex justify-between items-center">
                <div class="header-title">产品基础信息</div>
                <div v-if="permission_sku_info && current_sku.id">
                  <el-button
                    type="primary"
                    @click="handleRegionSave('goods_sku_info', current_sku)"
                    >保存SKU基础信息</el-button
                  >
                </div>
              </div>
              <SellInfo
                v-model="current_sku"
                class="line"
                @changeGeneralactive="changeGeneralactive"
              ></SellInfo>
            </el-card>
            <el-card class="box-card mt-2 card-content-line" shadow="never">
              <div id="peopleInfo" class="flex justify-between items-center peopleInfo">
                <div class="header-title">处理人员信息</div>
                <div v-if="permission_people_info && current_sku.id">
                  <el-button
                    type="primary"
                    @click="handleRegionSave('goods_sku_user', current_sku)"
                    >保存处理人员</el-button
                  >
                </div>
              </div>
              <PeopleInfo ref="peopleInfoRef" v-model="current_sku"></PeopleInfo>
            </el-card>
            <el-card class="box-card mt-2 card-content-line" shadow="never">
              <div
                id="weightSizeInfo"
                class="flex justify-between items-center weightSizeInfo"
              >
                <div class="header-title">产品重量尺寸</div>
                <div>
                  <el-button
                    v-if="handleType != 'view' && form.goods_sku.length > 1"
                    @click="copySKUFun('weightSizeInfo')"
                    :disabled="permission_all"
                    >复制重量尺寸信息</el-button
                  >
                  <template v-if="permission_weight_size && current_sku.id">
                    <el-button
                      type="primary"
                      @click="handleRegionSave('goods_sku_weight', current_sku)"
                      >保存重量尺寸</el-button
                    >
                  </template>
                </div>
              </div>
              <weightSizeInfo
                ref="weightSizeInfoRef"
                v-model="current_sku"
                class="line"
              ></weightSizeInfo>
            </el-card>
            <el-card class="box-card mt-2 card-content-noline border-card" shadow="never">
              <div id="pictureId" class="pictureId">
                <Picture
                  ref="pictureRef"
                  v-model="current_sku.goods_sku_gallery"
                  :currentIndex="current_index"
                  @copySKUFun="copySKUFun"
                >
                  <template #handle>
                    <div
                      v-if="permission_picture && current_sku.id"
                      class="absolute top-0 right-0 z-[98]"
                    >
                      <el-button
                        type="primary"
                        @click="handleRegionSave('goods_sku_image', current_sku)"
                        >保存图片</el-button
                      >
                    </div>
                  </template>
                </Picture>
              </div>
            </el-card>
            <el-card
              class="box-card mt-2 flex w-full tabs-style card-content-noline border-card"
              shadow="never"
            >
              <Remark v-model="current_sku.goods_sku_remark" id="SKURemark">
                <template #header>
                  <div class="flex justify-between">
                    <div class="header-title mt-[8px]">备注信息</div>
                  </div>
                </template>
                <template #handle>
                  <div
                    v-if="permission_remark && current_sku.id"
                    class="absolute top-0 right-0 z-[98]"
                  >
                    <el-button
                      type="primary"
                      @click="handleRegionSave('goods_sku_remark', current_sku)"
                      >保存备注</el-button
                    >
                  </div>
                </template>
              </Remark>
            </el-card>

            <el-card
              class="box-card mt-2 w-full tabs-content-border certificate-card"
              shadow="never"
            >
              <Certificate
                ref="CertificateRef"
                v-model="current_sku.goods_sku_certificate"
              >
                <template #header>
                  <div id="certificateFile" class="header-title mb-2">证书/文件</div>
                </template>
                <template #handle>
                  <div
                    v-if="permission_certificate && current_sku.id"
                    class="absolute top-0 right-0 z-[98]"
                  >
                    <el-button
                      type="primary"
                      @click="handleRegionSave('goods_sku_certificate', current_sku)"
                      >保存证书/文件</el-button
                    >
                  </div>
                </template>
              </Certificate>
            </el-card>

            <el-card class="box-card mt-2 w-full tabs-content-border" shadow="never">
              <recommend
                v-model="current_sku.goods_sku_recommended_platform"
                :info="{
                  packing_size_cm: current_sku.packing_size_cm,
                  package_weight: current_sku.gross_weight_g,
                }"
              >
                <template #header>
                  <div id="platformSite" class="header-title">推荐平台/站点</div>
                </template>
                <template #handle>
                  <div v-if="permission_platform && current_sku.id" class="ml-2">
                    <el-button
                      type="primary"
                      @click="
                        handleRegionSave('goods_sku_recommended_platform', current_sku)
                      "
                      >保存推荐平台/站点</el-button
                    >
                  </div>
                </template>
              </recommend>
            </el-card>

            <el-card
              class="box-card mt-2 tabs-content-border"
              shadow="never"
              id="GeneralInfoRef"
            >
              <el-tabs
                v-model="generalactive"
                type="card"
                class="header-mb0"
                @tab-change="changeTab($event, index)"
              >
                <el-tab-pane label="供应商信息" name="Supplier" />
                <el-tab-pane label="商品描述" name="2" />
                <el-tab-pane label="组合SKU" name="4" v-if="current_sku.is_combination" />
                <el-tab-pane label="产品头程运费设置" name="8"> </el-tab-pane>
                <el-tab-pane label="渠道SKU" name="5" />
                <el-tab-pane label="拿样记录" name="6" />
                <el-tab-pane
                  label="关联辅料"
                  name="7"
                  v-if="current_sku.sku_product_type != 2"
                />
                <el-tab-pane
                  v-if="
                    !current_sku.is_relation_sku &&
                    current_sku.goods_sku_relation_old?.is_change_sku != 1
                  "
                  label="切换SKU"
                  name="9"
                />
              </el-tabs>
              <div class="card-body">
                <div class="header-title inline-block">SKU综合信息</div>
                <div v-if="generalactive == 'Supplier'">
                  <Supplier
                    ref="supplierRef"
                    v-model="current_sku.goods_sku_supplier"
                    :custom_sku="current_sku.custom_sku"
                    :sku="current_sku.sku"
                    :skuIndex="current_index"
                    :info="{
                      custom_sku: current_sku.custom_sku,
                      sku: current_sku.sku,
                      sku_product_type: current_sku.sku_product_type,
                      dev_status: current_sku.dev_status,
                      sku_id: current_sku.id,
                      spu_category: form.spu_category,
                      is_dangerous: current_sku.is_dangerous,
                      brand_name: current_sku.goods_sku_sales_info?.brand_name,
                      is_add_sku: is_add_sku,
                      logistics_attributes: form.logistics_attributes,
                      is_combination: current_sku.is_combination,
                    }"
                    @copySKU="copySKUFun"
                    @queryDetail="queryDetail('edit')"
                  >
                  </Supplier>
                </div>
                <div v-show="generalactive == '2'">
                  <Ddescribe
                    ref="DdescribeRef"
                    v-model="current_sku.goods_sku_description"
                  >
                    <template #handle>
                      <div
                        class="ml-2 -mt-[36px]"
                        v-if="permission_product_description && current_sku.id"
                      >
                        <el-button
                          type="primary"
                          @click="handleRegionSave('goods_sku_description', current_sku)"
                          >保存商品描述</el-button
                        >
                      </div>
                    </template>
                  </Ddescribe>
                </div>
                <div v-if="generalactive == '4'">
                  <GroupSku
                    ref="GroupSkuRef"
                    v-model="current_sku.goods_sku_combination_sku"
                  >
                    <template #title>
                      <div class="mr-10 text-xl font-bold">
                        组合类型：{{
                          current_sku.combined_sources == 1
                            ? "开发组合"
                            : current_sku.combined_sources == 2
                            ? "销售组合"
                            : current_sku.combined_sources == 3
                            ? "拆包组合"
                            : ""
                        }}
                      </div>
                    </template>
                    <template #handle>
                      <div
                        class="ml-2"
                        v-if="permission_combination_sku && current_sku.id"
                      >
                        <el-button
                          type="primary"
                          @click="
                            handleRegionSave('goods_sku_combination_sku', current_sku)
                          "
                          >保存组合SKU</el-button
                        >
                      </div>
                    </template>
                  </GroupSku>
                </div>
                <div v-if="generalactive == '8'">
                  <HeadFreight
                    ref="headFreightRef"
                    v-model="current_sku.goods_sku_head_freight"
                    :info="{
                      sku: current_sku.sku,
                      sku_id: current_sku.id,
                      gross_weight_g: current_sku.gross_weight_g,
                      packing_size_cm: current_sku.packing_size_cm,
                      goods_sku_supplier: current_sku.goods_sku_supplier,
                      exchange_rate: exchange_rate,
                    }"
                  ></HeadFreight>
                </div>
                <ChannelSku
                  ref="ChannelSkuRef"
                  :custom_sku="current_sku.custom_sku"
                  v-if="generalactive == '5'"
                >
                </ChannelSku>
                <Sample ref="SampleRef" v-if="generalactive == '6'"> </Sample>
                <Ingredient
                  class="border border-t-0 py-2 px-2"
                  ref="IngredientRef"
                  v-model="current_sku.goods_sku_accessories"
                  :custom_sku="current_sku.custom_sku"
                  :sku="current_sku.sku"
                  :item="current_sku"
                  v-if="generalactive == '7'"
                >
                  <template #handle>
                    <div class="ml-2" v-if="permission_ingredient_info && current_sku.id">
                      <el-button
                        type="primary"
                        @click="handleRegionSave('goods_sku_accessories', current_sku)"
                        >保存辅料</el-button
                      >
                    </div>
                  </template>
                </Ingredient>
                <SwitchSKU
                  v-model="current_sku.goods_sku_relation"
                  :current_sku="current_sku.sku"
                  v-if="generalactive == '9'"
                >
                  <template #handle>
                    <div class="ml-2" v-if="permission_ingredient_info && current_sku.id">
                      <el-button
                        type="primary"
                        @click="handleRegionSave('goods_sku_relation', current_sku)"
                        >保存切换SKU</el-button
                      >
                    </div>
                  </template>
                </SwitchSKU>
              </div>
              <div id="bottom" ref="bottomRef"></div>
            </el-card>
          </div>
        </el-card>
      </div>
      <div class="sidebar">
        <el-affix :offset="affixtab ? 85 : 85">
          <div class="broadside w-52 mr-1.5 px-6">
            <div
              :class="[
                'broadside-item cursor-pointer',
                item.name == scrollPosition.activeModule ? 'active' : '',
              ]"
              v-for="(item, index) in filteredSKUItems"
              :key="index"
              @click="scrollTop(item.name, item.offset)"
            >
              {{ item.label }}
            </div>
          </div>
          <div
            :class="[
              'mt-3 roll',
              scrollPosition.isTopBottom == 'top' ? 'rollActive' : '',
            ]"
            @click="scrollTop('top')"
          >
            <svg-icon
              class="text-[32px] text-[--base-color]"
              icon-class="roll-top"
            ></svg-icon>
          </div>
          <div
            :class="[
              'mt-3 roll',
              scrollPosition.isTopBottom == 'bottom' ? 'rollActive' : '',
            ]"
            @click="scrollTop('bottom')"
          >
            <svg-icon
              class="text-[32px] text-[--base-color]"
              icon-class="roll-down"
            ></svg-icon>
          </div>
        </el-affix>
      </div>
      <div class="handle flex justify-center items-center py-4 fixed bottom-0 z-index">
        <div class="flex justify-start items-center" v-if="handleType != 'view'">
          <el-checkbox v-model="form.is_notify" label="消息通知审核人员" size="large" />
          <select-personnel
            class="ml-2"
            v-model="form.dev_reviewer_id"
            placeholder="请选择"
          ></select-personnel>
        </div>
        <div class="ml-10 mr-20">
          <el-button :type="handleType == 'view' ? 'primary' : ''" @click="back"
            >返回</el-button
          >

          <template v-if="handleType != 'view'">
            <el-button type="primary" plain @click="handleInfringement"
              >检测侵权</el-button
            >
            <el-button type="primary" @click="save">保存并继续编辑</el-button>
            <!-- <el-checkbox
              class="ml-4"
              v-model="form.is_push_to_saihe"
              label="推送赛盒"
              :true-label="1"
              :false-label="0"
              size="large"
            /> -->
            <!-- <template v-if="form.dev_status == 2 || form.dev_status == 3">
              <el-button class="ml-2" type="primary" @click="handleAudit(true)">审核通过</el-button>
              <el-button type="danger" @click="handleAudit(false)">审核不通过</el-button>
            </template> -->
          </template>
        </div>
        <div
          class="flex justify-start items-center text-gray-400 mt-2 text-xs"
          v-if="handleType != 'view'"
        >
          <svg-icon icon-class="hint_line" />
          系统自动保留未提交的信息，未保存的信息有效期为24H，请及时保存。
        </div>
      </div>
    </div>
    <el-dialog v-model="dialogVisible" title="提示" width="30%" align-center draggable>
      <div v-html="errorMessage"></div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="confirmNew">获取最新数据</el-button>
          <el-button type="primary" @click="confirmCover">确认覆盖</el-button>
        </span>
      </template>
    </el-dialog>
    <InfringementDetection ref="infringementRef"></InfringementDetection>
    <copySKU ref="copySKURef"></copySKU>
  </div>
</template>

<script name="TaskProductEdit" setup>
import SpuInfo from "../componentsDetail/SpuInfo.vue";
import SellInfo from "../componentsDetail/SellInfo.vue";
import PeopleInfo from "../componentsDetail/PeopleInfo.vue";
import MultiAttribute from "../componentsDetail/Attribute/index.vue";
import Picture from "../componentsDetail/Picture/index.vue";
import Remark from "../componentsDetail/Remark.vue";
import Certificate from "../componentsDetail/Certificate/index.vue";
import Flow from "../componentsDetail/Flow.vue";
import Ddescribe from "../componentsDetail/GeneralInfo/Ddescribe.vue";
import Supplier from "../componentsDetail/Supplier/index";
import GroupSku from "../componentsDetail/GeneralInfo/GroupSku.vue";
import ChannelSku from "../componentsDetail/GeneralInfo/ChannelSku.vue";
import Sample from "../componentsDetail/GeneralInfo/Sample/index";
import Ingredient from "../componentsDetail/GeneralInfo/Ingredient/index";
import recommend from "../componentsDetail/GeneralInfo/recommend/index";
import weightSizeInfo from "../componentsDetail/weightSizeInfo.vue";
import copySKU from "../componentsDetail/copySKU.vue";
import HeadFreight from "../componentsDetail/HeadFreight/index";
import { getOptions } from "@/api/index.js";
import {
  goodsEdit,
  getDetail,
  infringementDetection,
  review,
  lock,
  unLock,
  getLock,
  getSKUDetails,
  goodsRegionSave,
  isRelation,
} from "../api";
import { computed, nextTick, reactive, ref, toRaw, toRefs } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import useCommonStore from "@/store/modules/common";
import { storeToRefs } from "pinia";
const commonStore = useCommonStore();
const { languageOptions } = storeToRefs(commonStore);
import action from "@/utils/action.js";
import InfringementDetection from "../componentsDetail/InfringementDetection.vue";
import { deepClone } from "@/utils/index";
import { scrollToError } from "@/hooks/formScroll.js";
import { queryBaseHeadFreightList } from "@/views/basics/reference-freight/api.js";
import { getCurrency } from "../api.js";
import { checkDuplicateAttributes, handletTwiceConfirm } from "@/utils/product/index.js";
import { imageTypeText, regionNameMap } from "../data.js";
import {
  product_identification_image,
  tag_style_image,
  classified_overseas_position,
  classified_auto_parts,
} from "@/utils/product/data.js";
import SwitchSKU from "../componentsDetail/GeneralInfo/SwitchSKU/index.vue";
import { debounce } from "@/utils/dom.js";

const route = useRoute();
const router = useRouter();
const data = reactive({
  form: {
    spu: "",
    spu_category: [],
    is_notify: false,
    imitation_remark: "",
    is_notify: false,
    need_photo: 1,
    need_processing: 2,
    recommended_level: "",
    brand_id: "",
    brand_type: 1,
    authentication: [],
    spu_cn_title: "",
    spu_en_title: "",
    specifications: "",
    spu_status: 1,
    goods_source: 1,
    goods_sku: [],
    goods_spu_sales_info: {
      suggested_sales_price: "",
      currency: "",
      currency_id: "",
      warehouse_id: "",
      logistics_attributes: "",
      suggested_header_channel: "",
      custom_specification: [],
      competing_products_link: [""],
      spu_unit: "",
      packaging_method: "",
      plug_specification: "",
    },
    developer_id: "",
    purchaser_id: null,
    dev_reviewer_id: null,
    quality_inspector_id: null,
    img_processor_id: null,
    editor_id: null,
    goods_spu_prohibited_sales: [{ prohibited_platform: "", prohibited_site: "" }],
  },
  dialogVisible: false,
  errorMessage: "",
  handleType: null,
  spuId: null,
  activeName: null,
  goods_spu_gallery: null,
  generalactive: "Supplier",
  sku: null,
  goods_sku_list: [],
  sku_product_type: null,
  add_sku_info: {},
});
let {
  form,
  dialogVisible,
  errorMessage,
  handleType,
  spuId,
  activeName,
  goods_spu_gallery,
  generalactive,
  sku,
  goods_sku_list,
  sku_product_type,
  add_sku_info,
} = toRefs(data);
const options = ref([]);
const creatSkuInfo = ref({});
provide("options", options);
provide("form", form);
provide("handleType", handleType);
provide("sku_product_type", sku_product_type);
provide(
  "creatSkuInfo",
  computed(() => {
    return creatSkuInfo.value;
  })
);

provide("add_sku_info", add_sku_info);

const current_sku = computed(() => {
  return form.value.goods_sku.find((item) => item.sku === activeName.value);
});

const current_index = computed(() => {
  return form.value.goods_sku.findIndex((item) => item.sku === activeName.value);
});

console.log("current_sku.value");
console.log(current_sku.value);

// 语言
const getLanguageList = async () => {
  commonStore.getLanguageList();
};
getLanguageList();

// 下拉数据
const fetchOption = async () => {
  const res = await getOptions({
    name: [
      "goods.GoodsSpu",
      "goods.GoodsSku",
      "goods.GoodsSkuSalesInfo",
      "goods.GoodsSkuSupplier",
      "goods.GoodsSkuAccessories",
      "goods.GoodsSkuSupplier",
      "gallery.GoodsSkuGalleryContents",
      "goods.GoodsSkuIdentificationProcessing",
      "goods.GoodsSkuCertificate",
    ],
  });
  options.value = res.data;
  initGallery();
};

//加锁
const lockSpu = async () => {
  const { spuId } = route.query;
  if (!spuId) return;
  try {
    await lock({
      spuId,
    });
  } catch (e) {
    throw Error(e);
  }
};
//解锁
const unLockSpu = async () => {
  const { spuId } = route.query;
  if (!spuId) return;
  try {
    await unLock({
      spuId,
    });
  } catch (e) {
    throw Error(e);
  }
};
// 初始化默认产品图片一个标签
const initGallery = (isreturn = false) => {
  let obj = {
    custom_tag: "默认",
    spu: form.spu,
    spu_category: form.value.spu_category,
    spu_cn_title: form.value.spu_cn_title,
    contents: [],
  };
  imageTypeText.forEach((element, e) => {
    obj.contents.push({
      label: element.label,
      image_type: element.value,
      showType: 0,
      values: [],
    });
  });
  if (isreturn) {
    return [obj];
  } else {
    goods_spu_gallery.value = [obj];
  }
};
initGallery();

const initGalleryContents = () => {
  let contents = [];
  imageTypeText.forEach((element, e) => {
    contents.push({
      label: element.label,
      image_type: element.value,
      showType: 0,
      values: [],
    });
  });
  return contents;
};

const CertificateRef = ref();
const FlowRef = ref();
const spuInfoRef = ref();
const queryDetail = async (type) => {
  try {
    const res = await getDetail({
      spuId: spuId.value,
      fromEdit: true,
    });
    nextTick(async () => {
      let againData = res.data;

      const sku_ids = againData.goods_sku.map((item) => item.id);
      const isRelation_sku = await getisRelation(sku_ids);

      againData.goods_sku = againData.goods_sku.map((i) => {
        i.goods_sku_gallery =
          i.goods_sku_gallery && i.goods_sku_gallery.length
            ? i.goods_sku_gallery.map((j) => {
                if (j.contents.length == 0) {
                  j.contents = initGalleryContents();
                } else {
                  j.contents = matchAndAdd(
                    goods_spu_gallery.value[0].contents,
                    j.contents
                  );
                  j.contents = j.contents.sort(
                    (a, b) => gallerySort(a.image_type) - gallerySort(b.image_type)
                  );
                }
                return j;
              })
            : initGallery(true);
        i.goods_sku_sales_info = i.goods_sku_sales_info || {
          brand_id: "",
          brand_type: 1,
          suggested_sales_price: "",
          currency: "",
          currency_id: 158,
          currency_name: "USD",
          warehouse_id: "",
          logistics_attributes: "",
          suggested_header_channel: "",
          custom_specification:
            handleType.value == "edit" ? [{ name: "", value: "" }] : [],
          competing_products_link: [""],
          spu_unit: "",
          packaging_method: "",
          plug_specification: "",
          goods_spu_prohibited_sales:
            handleType.value == "edit"
              ? [{ prohibited_platform: "", prohibited_site: "" }]
              : [],
        };
        if (handleType.value == "edit") {
          i.goods_sku_prohibited_sales = i.goods_sku_prohibited_sales?.length
            ? i.goods_sku_prohibited_sales
            : [
                {
                  platform_name: "",
                  site_code: "",
                  platform_id: "",
                },
              ];

          i.goods_sku_authentication = i.goods_sku_authentication?.length
            ? i.goods_sku_authentication
            : [
                {
                  country: [],
                  authentication_type: "",
                  authentication_name: "",
                },
              ];

          i.goods_sku_sell_month = i.goods_sku_sell_month?.length
            ? i.goods_sku_sell_month
            : [
                {
                  country: [],
                  hot_sell_month_start: "",
                  hot_sell_month_end: "",
                },
              ];
        }

        i.goods_sku_remark = i.goods_sku_remark || {
          dev_remark: "",
          purchase_remark: "",
          inspection_remark: "",
          packaging_remark: "",
        };
        i.goods_sku_customs = i.goods_sku_customs || {
          cn_name: "",
          en_name: "",
          purpose: "",
          cn_material: "",
          en_material: "",
          declare_elements: "",
          customs_code: "",
          tax_rebate_rate: "",
          declare_price_usd: "",
          declare_unit: "",
          declare_link: "",
          declare_link_price_eur: "",
        };

        i.goods_sku_sales_info.custom_specification = i.goods_sku_sales_info
          .custom_specification?.length
          ? i.goods_sku_sales_info.custom_specification
          : [{ name: "", value: "" }];
        i.goods_sku_recommended_platform = i.goods_sku_recommended_platform || [];
        i.goods_sku_title =
          i.goods_sku_title &&
          i.goods_sku_title.map((j) => {
            j.show = true;
            return j;
          });
        i.main_img = i.attr_img;
        i.goods_sku_supplier = i.goods_sku_supplier
          .map((j) => {
            j.default_supplier = j.is_default_supplier;
            j.goods_sku_identification_processing = j.goods_sku_identification_processing.map(
              (k) => {
                if (k.product_identification == 3 || k.product_identification == 10) {
                  k.image = changeTagStyle(k.tag_style);
                } else if (k.product_identification) {
                  k.image = changeProductIdentification(k.product_identification);
                }
                return k;
              }
            );
            return j;
          })
          .sort((a, b) => {
            if (a.default_supplier === 1) return -1; // 将值为1的项放在前面
            if (b.default_supplier === 1) return 1; // 将值为1的项放在前面
            return 0;
          });

        i.old_clean_product_status = i.clean_product_status;
        i.old_sales_status = i.sales_status;
        i.old_sku_product_type = i.sku_product_type;
        const find_relation_sku = isRelation_sku.find((item) => item.sku_id === i.id);
        i.is_relation_sku = find_relation_sku?.exist;
        i.goods_sku_relation_old = i.goods_sku_relation_old
          ? i.goods_sku_relation_old
          : {};
        if (i.is_relation_sku) {
          i.goods_sku_relation_old.is_change_sku = 1;
          i.goods_sku_relation_old.old_sku = i.goods_sku_relation_old.goods_sku;
        }
        if (i.goods_sku_relation?.length) {
          i.disabled_relation = true;
        }
        // if (i.goods_sku_relation.length == 0 && i.goods_sku_relation_old.is_change_sku ) {
        //   i.is_relation_sku = true;
        // }
        return i;
      });
      againData.goods_spu_specification = againData.goods_spu_specification?.length
        ? matchSpecification(againData.goods_spu_specification)
        : creatSpecification(againData.goods_sku[0].sku_specification);
      // againData.is_push_to_saihe = 1;

      form.value = againData;

      activeName.value = sku.value || form.value.goods_sku[0]?.sku;
      goods_sku_list.value = form.value.goods_sku;
      form.value.is_dangerous = form.value.base_logistics_attributes?.is_dangerous;
      // 初始化计时器活跃 防止计时器完结进入其他商品 导致无法解锁的情况
      // timerActive.value = false;
      // handleResize();
      FlowRef.value.init();
      if (route.query?.roll) {
        setTimeout(() => {
          scrollTop(route.query.roll);
        }, 500);
      }
    });
  } catch (e) {
    throw Error(e);
  }
};

//
const getisRelation = async (sku_ids) => {
  try {
    const res = await isRelation({
      sku_ids,
    });
    return res.data;
  } catch (e) {}
};

const matchAndAdd = (array1, array2) => {
  for (var i = 0; i < array1.length; i++) {
    var isDuplicate = false;
    for (var j = 0; j < array2.length; j++) {
      if (array1[i].image_type === array2[j].image_type) {
        isDuplicate = true;
        break;
      }
    }
    if (!isDuplicate) {
      array2.push(array1[i]);
    }
  }
  return array2;
};

const matchSpecification = (goods_spu_specification) => {
  const list = goods_spu_specification.map((spec) => {
    const updatedValues = [];

    spec.values.forEach((valueObj) => {
      const copyValue = { ...valueObj, show: true };
      updatedValues.push(copyValue);
    });

    const existingLanguageIds = new Set(
      updatedValues.map((valueObj) => valueObj.language_id)
    );

    if (languageOptions && languageOptions.value) {
      languageOptions.value.forEach((d) => {
        if (!existingLanguageIds.has(d.id)) {
          const copyValue = {
            language_id: d.id,
            language_name: d.name,
            language_code: d.short_name,
            is_relation_img: 0,
            show: d.id === 1 || d.id === 2 || d.id === 10,
            language_values: spec.values[0].language_values.map((v) => ({
              ...v,
              language_id: d.id,
              language_name: d.name,
              language_code: d.short_name,
              id: "",
              value: "",
            })),
          };
          updatedValues.push(copyValue);
        } else {
          updatedValues.forEach((valueObj) => {
            if (valueObj.language_id === d.id) {
              valueObj.show = d.id === 1 || d.id === 2 || d.id === 10;
            }
          });
        }
      });
    }

    spec.values = updatedValues.sort((a, b) => a.language_id - b.language_id);
    return spec;
  });

  return list;
};

const gallerySort = (type) => {
  if (type == 3) {
    return 0;
  } else {
    return type;
  }
};

// 修改spu 需要重置sku
const DdescribeRef = ref();
const initsku = () => {
  initGallery(options.value);
  DdescribeRef.value.getAttribute();
};

const back = () => {
  if (handleType.value == "view") {
    action.setGlobalState({
      changeMicoTabsPath: {
        type: "closeActiveTab",
      },
    });
  } else {
    ElMessageBox.confirm("确认返回将关闭当前页面", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      action.setGlobalState({
        changeMicoTabsPath: {
          type: "closeActiveTab",
        },
      });
    });
  }
};

// 编辑保存
const peopleInfoRef = ref();
const multiAttributeRef = ref();
const weightSizeInfoRefs = ref([]);
const peopleInfoRefs = ref([]);
const pictureRefs = ref([]);
const supplierRefs = ref();
const headFreightRefs = ref();
// watch(
//   () => form.value?.goods_sku?.length,
//   (val) => {
//     updateSellInfoRefs();
//   }
// );
// const updateSellInfoRefs = () => {
//   weightSizeInfoRefs.value = form.value?.goods_sku?.map((_, index) =>
//     ref(`weightSizeInfoRef${index}`)
//   );
//   pictureRefs.value = form.value?.goods_sku?.map((_, index) => ref(`pictureRef${index}`));
//   supplierRefs.value = form.value?.goods_sku?.map((_, index) =>
//     ref(`supplierRef${index}`)
//   );
//   peopleInfoRefs.value = form.value?.goods_sku?.map((_, index) =>
//     ref(`peopleInfoRef${index}`)
//   );
//   headFreightRefs.value = form.value?.goods_sku?.map((_, index) =>
//     ref(`headFreightRef${index}`)
//   );
// };

const weightSize_permission = computed(() => {
  return (window.BTN_AUTH || []).includes("/goods/task/product/weight-size-info");
});

const save = async () => {
  await spuInfoRef.value.validate();
  await multiAttributeRef.value.validate();
  let flag = true;
  for (let i = 0; i < form?.value?.goods_sku?.length; i++) {
    activeName.value = form.value.goods_sku[i].sku;
    await new Promise((resolve) => setTimeout(resolve, 0)); // 等待下一个事件循环
    await nextTick(async () => {
      try {
        if (
          permission_weight_size.value &&
          (!form.value?.goods_sku[i]?.gross_weight_g ||
            !form.value?.goods_sku[i]?.net_weight_g)
        ) {
          scrollToError(document.querySelector(".weightSizeInfo"));
          ElMessage.warning("产品毛重和净重不能为空!");
          throw new Error("这是一个错误");
        }
        if (!form.value?.goods_sku[i]?.attr_img) {
          scrollToError(document.querySelector(".pictureId"));
          ElMessage.warning("产品图片中至少需要一张图片作为主图!");
          throw new Error("这是一个错误");
        }
        if (
          permission_general.value &&
          !form?.value?.goods_sku[i]?.goods_sku_supplier?.length &&
          form?.value?.goods_sku[i]?.is_combination != 1
        ) {
          scrollToError(document.querySelector(".GeneralInfoRef"));
          ElMessage.warning("请至少添加一条供应商信息!");
          throw new Error("这是一个错误");
        }
        const findIndex = form.value?.goods_sku[
          i
        ]?.goods_sku_recommended_platform.findIndex((i) => i.platform_name == "amazon");

        if (
          classified_overseas_position.includes(
            form.value.spu_category ? form.value.spu_category[0] : ""
          ) ||
          (findIndex == -1 &&
            classified_auto_parts.includes(
              form.value.spu_category ? form.value.spu_category[0] : ""
            ) &&
            weightSize_permission.value)
        ) {
          const { length, width, height } = form.value?.goods_sku[i]?.packing_size_cm;
          const dimensions = [length, width, height].sort((a, b) => a - b);
          if (!(dimensions[0] > 0 && dimensions[1] >= 10 && dimensions[2] >= 15)) {
            const sku_ids = form.value?.goods_sku[i]?.goods_sku_accessories
              .filter((i) => !i.delete)
              .map((i) => i.accessory_sku_id);
            const is_satisfy = await checkSKUAccessories(sku_ids);
            if (!is_satisfy) {
              scrollToError(document.querySelector(".weightSizeInfo"));
              ElMessage.warning(
                "海外仓SKU的包装尺寸或者绑定的辅料包装尺寸，至少有一边>=10cm;一边>=15cm且必须>0，当前SKU未满足，请核实；若有疑问可咨询物流部"
              );
              throw new Error("这是一个错误");
            }
          }
        }

        if (
          form.value?.goods_sku[i]?.goods_sku_relation_old?.is_change_sku == 1 &&
          !form.value?.goods_sku[i]?.goods_sku_relation_old?.old_sku
        ) {
          scrollToError(document.querySelector(".SKUInfo"));
          ElMessage.warning("是否切换SKU=是，旧SKU必填");
          throw new Error("这是一个错误");
        }
      } catch (error) {
        flag = false;
        return;
      }
    });
    if (!flag) return;
  }
  if (!flag) return;

  const newForm = deepClone(form.value);

  const result = checkDuplicateAttributes(newForm.goods_sku);
  if (result.duplicate) {
    const repetition = Object.values(result.attributes);
    ElMessage.warning(`发现重复属性: ${repetition.join(",")} `);
    return;
  }

  if (result.nullValue) {
    ElMessage.warning(`SKU属性值不能为空，请检查`);
    return;
  }

  newForm.goods_sku = newForm.goods_sku.map((item) => {
    item.goods_sku_description =
      item.goods_sku_description?.length &&
      item.goods_sku_description.filter((j) => {
        if (j.show != false) {
          return j;
        }
      });

    item.goods_sku_title =
      item.goods_sku_title &&
      item.goods_sku_title.filter((i) => {
        if (i.show && i.language_id) {
          return i;
        }
      });
    item.goods_sku_gallery = item.goods_sku_gallery.map((i) => {
      i.contents = i.contents
        .filter((j) => j.values.length > 0)
        .map((k) => {
          k.values = k.values.map((v, w) => {
            v.sort = w;
            return v;
          });
          return k;
        });
      return i;
    });
    item.goods_sku_remark.edit_remark =
      item.goods_sku_remark.edit_remark == "<p><br></p>"
        ? ""
        : item.goods_sku_remark.edit_remark;
    item.goods_sku_remark.inspection_remark =
      item.goods_sku_remark.inspection_remark == "<p><br></p>"
        ? ""
        : item.goods_sku_remark.inspection_remark;
    item.goods_sku_prohibited_sales =
      item.goods_sku_prohibited_sales &&
      item.goods_sku_prohibited_sales.filter((j) => {
        if (j.platform_id && j.site_code) {
          return j;
        }
      });
    item.goods_sku_authentication = item.goods_sku_authentication.filter((j) => {
      if (j.country.length > 0 && j.authentication_name) {
        return j;
      }
      if (j.id && j.country.length == 0 && !j.authentication_name) {
        j.delete = 1;
        return j;
      }
    });
    // item.goods_sku_sell_month = item.goods_sku_sell_month
    //   .map((j) => {
    //     if (
    //       j.id &&
    //       (j.country?.length == 0 ||
    //         !j.hot_sell_start_month ||
    //         !j.hot_sell_end_month ||
    //         !j.remark)
    //     ) {
    //       j.delete = 1;
    //     }
    //     return j;
    //   })
    //   .filter((i) => {
    //     if (
    //       i.delete ||
    //       i.id ||
    //       i.country?.length > 0 ||
    //       i.hot_sell_start_month ||
    //       i.hot_sell_end_month ||
    //       i.remark
    //     ) {
    //       return i;
    //     }
    //   });

    item.goods_sku_accessories = item.goods_sku_accessories.map((j) => {
      if (!j.sku) {
        j.sku = "";
      }
      return j;
    });
    item.gross_weight_g = item.gross_weight_g || 0;
    item.net_weight_g = item.net_weight_g || 0;
    item.packing_weight_g = item.packing_weight_g || 0;
    item.packing_size_cm = {
      length: item.packing_size_cm.length || 0,
      width: item.packing_size_cm.width || 0,
      height: item.packing_size_cm.height || 0,
    };
    item.product_size_cm = {
      length: item.product_size_cm.length || 0,
      width: item.product_size_cm.width || 0,
      height: item.product_size_cm.height || 0,
    };
    item.packing_qty_size_cm = {
      length: item.packing_qty_size_cm.length || 0,
      width: item.packing_qty_size_cm.width || 0,
      height: item.packing_qty_size_cm.height || 0,
    };
    item.packing_gross_weight_kg = item.packing_gross_weight_kg || 0;
    item.cabinets_qty = item.cabinets_qty || 0;
    item.packing_qty = item.packing_qty || 0;

    item.goods_sku_head_freight = item.goods_sku_head_freight
      ?.filter((j) => {
        if (j.id || j.single_freight || j.single_tax_fee) {
          return j;
        }
      })
      .map((k) => {
        return {
          id: k.id,
          base_head_freight_id: k.base_head_freight_id,
          single_freight: k.single_freight || 0,
          single_tax_fee: k.single_tax_fee || 0,
        };
      });
    item.goods_sku_sell_month = item.goods_sku_sell_month.filter((i) => {
      return !(
        Array.isArray(i.country) &&
        i.country.length === 0 &&
        !i.hot_sell_start_month &&
        !i.hot_sell_end_month
      );
    });
    return item;
  });

  newForm.goods_spu_specification = newForm.goods_spu_specification
    .filter((j) => {
      if (j.show != false) {
        return j;
      }
    })
    .map((i) => {
      i.values =
        i.values.length &&
        i.values.filter((i) => {
          if (i.show && i.language_id && i.name) {
            return i;
          }
        });
      return i;
    });

  goodsEdit(newForm)
    .then((res) => {
      ElMessage.success(res.message);
      if (res.data.spu_id) {
        spuId.value = res.data.spu_id;
      }
      handleType.value = "edit";
      if (newForm.goods_sku.length == 1 && generalactive.value == 8) {
        const firstHeadFreightRef = headFreightRefs.value[0];
        // 确保firstHeadFreightRef是一个对象并且有calculateFreight方法
        if (typeof firstHeadFreightRef.value[0].init === "function") {
          // 调用方法
          setTimeout(() => {
            firstHeadFreightRef.value[0].init();
          }, 500);
        } else {
          console.error("init 方法未定义");
        }
      }
      initGallery();
      queryDetail("edit");
    })
    .catch((err) => {
      if (err.code == 20002) {
        errorMessage.value = err.message;
        dialogVisible.value = true;
      }
    });
};

const confirmNew = () => {
  dialogVisible.value = false;
  queryDetail("edit");
};

const confirmCover = () => {
  form.value.confirm_cover = true;
  dialogVisible.value = false;
  save();
};

// 锚点
const sideDataref = reactive({
  sideData: [
    {
      label: "SPU信息",
      name: "top",
    },
    {
      label: "多属性设置",
      name: "multiattribute",
    },
    {
      label: "SKU基础信息",
      name: "SKUInfo",
      offset: true,
    },
    {
      label: "SKU人员信息",
      name: "peopleInfo",
      offset: true,
    },
    {
      label: "SKU重量尺寸",
      name: "weightSizeInfo",
      offset: true,
    },
    {
      label: "SKU图片",
      name: "pictureId",
      offset: true,
    },
    {
      label: "SKU备注",
      name: "SKURemark",
      offset: true,
    },
    {
      label: "SKU证书/文件",
      name: "certificateFile",
      offset: true,
    },
    {
      label: "SKU推荐平台/站点",
      name: "platformSite",
      offset: true,
    },
    {
      label: "SKU综合信息",
      name: "GeneralInfoRef",
      offset: true,
    },
    {
      label: "保存/审核",
      name: "bottom",
      offset: true,
    },
  ],
});

const { sideData } = toRefs(sideDataref);

const filteredSKUItems = computed(() => {
  if (form.value.goods_sku?.length) {
    return sideData.value;
  } else {
    return sideData.value.slice(0, 3);
  }
});

const scrollPosition = reactive({
  top: 0,
  activeModule: "top",
  isTopBottom: "top",
});

const computedHeight = (e) => {
  if (e.currentTarget.scrollTop <= 1) {
    scrollPosition.isTopBottom = "top";
  } else if (
    e.currentTarget.scrollTop + e.currentTarget.clientHeight >=
    e.currentTarget.scrollHeight
  ) {
    scrollPosition.isTopBottom = "bottom";
  } else {
    scrollPosition.isTopBottom = "";
  }
};

const scrollContainer = ref();
const handleScroll = (event) => {
  let height = document.getElementById("scrollContainer").scrollTop;
  let heightSKu = document.querySelector(`#SKUOffsetTop`).offsetTop + 40;
  if (height >= heightSKu) {
    affixtab.value = form.value.goods_sku.length > 1 ? true : false;
  } else {
    affixtab.value = false;
  }
  scrollPosition.top = event.target.scrollTop;
  computedHeight(event);
  updateActiveModule();
};
const affixtab = ref(false);
const scrollTop = (selector, isOffset = false) => {
  nextTick(async () => {
    const element = document.querySelector(`#${selector}`);
    const offset = isOffset ? 45 : 0;
    if (element) {
      const height = element.offsetTop - offset;
      const container = document.querySelector("#scrollContainer");
      container.scrollTo({
        top: height,
        behavior: "smooth",
      });
    } else {
      console.warn(`Element with ID '${selector}' not found.`);
    }
  });
};

const updateActiveModule = () => {
  const containerTop = document.getElementById("scrollContainer").offsetTop + 45;
  const scrollPositionTop = scrollPosition.top;
  for (let i = 0; i < filteredSKUItems.value.length; i++) {
    let module = filteredSKUItems.value[i];
    const anchorElement = document.getElementById(module.name).offsetTop;
    const offset = module.offset ? -100 : 0;
    if (
      scrollPositionTop >= anchorElement + offset - containerTop &&
      (i === filteredSKUItems.value.length - 1 ||
        scrollPositionTop <
          (document.getElementById(filteredSKUItems.value[i + 1].name)?.offsetTop ||
            offset + 20) +
            offset -
            containerTop)
    ) {
      scrollPosition.activeModule = module.name;
      break;
    }
  }
};

// 初始化时长
const countdown = ref(5 * 60);
// 时长
const duration = 5 * 60;
// 锁定时长
const lockduration = 10;

const timerActive = ref(false);
let timer;
function startTimer() {
  timer = setInterval(async () => {
    if (countdown.value > 0) {
      countdown.value -= 1;
      // console.log("锁定");
      // console.log(countdown.value);
    }
    if (countdown.value == 0) {
      clearInterval(timer);
      // timerActive.value = true;
      try {
        if (!spuId.value) return;
        const res = await unLock({
          spuId: spuId.value,
        });
        if (res.code != 200) {
          ElMessage.warning(res.message);
        }
      } catch (e) {
        throw Error(e);
      }
      if (routeLeave.value) return;
      ElMessageBox.confirm(
        "您已五分钟未操作此编辑页面，已经自动解除锁定，数据可能已有其他同事正在操作，请确认，防止数据被覆盖。",
        "提示",
        {
          confirmButtonText: "确定",
          showClose: false,
          type: "warning",
          confirmButtonClass: "btnFalses",
          showCancelButton: false,
        }
      ).then(() => {});
    }
  }, 1000);
}
const clearTimer = () => {
  // 清除定时器
  clearInterval(timer);
};

const handleMouseMove = async () => {
  // console.log("锁定");
  // console.log(countdown.value);
  // if (timerActive.value) return;
  if (!spuId.value) return;
  if (countdown.value <= lockduration) {
    debouncedHandleLock();
  }
  // 用户鼠标移动，重置定时器
};

// 获取锁定 锁定 重置定时器
const handleLock = async () => {
  const { data } = await getLock({ spuId: spuId.value });
  if (data != 0) {
    ElMessageBox.confirm(
      `超过五分钟未进行编辑操作, 已有其他同事（${data}）正在编辑，请慎重操作保存，防止防止数据覆盖`,
      "提示",
      {
        confirmButtonText: "确定",
        showClose: false,
        type: "warning",
        confirmButtonClass: "btnFalses",
        showCancelButton: false,
      }
    ).then(() => {});
    clearTimer();
    return;
  }
  await lockSpu();
  clearTimer();
  startTimer();
  countdown.value = duration;
};

const debouncedHandleLock = debounce(handleLock, 1000);

//是否首次加载
const isFirstLoad = ref(true);
onMounted(async () => {
  isFirstLoad.value = false;
  fetchOption();
  handleType.value = route.query?.type;
  // await initPage()
  await getBaseHeadFreightList();
  await getExchangeRate();
  if (!commonStore.countryOptions) {
    commonStore.getCountryList();
  }
  startTimer();
  window.addEventListener("mousemove", handleMouseMove);
  // window.addEventListener("resize", handleResize);
});

// 综合信息tab切换
const changeTab = async (val, index) => {
  generalactive.value = val;
};

const initPage = async () => {
  sku.value = route.query?.sku;
  if (route.query?.spuId || route.query?.productId) {
    spuId.value = route.query?.spuId || route.query?.productId;
    if (handleType.value != "view") {
      await tipTab(spuId.value);
      await lockSpu();
    }
    await queryDetail(route.query.type);
  }
};

const tipTab = async (spuId) => {
  const { data } = await getLock({ spuId });
  if (data != 0) {
    ElMessageBox.confirm(`该产品[${data}]正在被编辑中，请稍后再试！`, "提示", {
      confirmButtonText: "确定",
      showClose: false,
      type: "warning",
      confirmButtonClass: "btnFalses",
      showCancelButton: false,
    }).then(() => {
      action.setGlobalState({
        changeMicoTabsPath: {
          type: "closeActiveTab",
        },
      });
    });
    return;
  }
};
const routeQuery = ref();
watch(
  router.currentRoute,
  (newRouter, oldRouter) => {
    if (newRouter.path == "/task/product/edit") {
      if (JSON.stringify(newRouter.query) !== "{}") {
        if (JSON.stringify(newRouter.query) != JSON.stringify(routeQuery.value)) {
          handleType.value = route.query?.type;
          routeQuery.value = newRouter.query;
          initPage();
          countdown.value = duration;
        }
        if (scrollPosition.top > 0) {
          setTimeout(() => {
            scrollTo(scrollPosition.top);
          }, 100);
        }
      }
    }
  },
  { immediate: true, deep: true }
);

// 跳转页面指定高度
const scrollTo = (height) => {
  const container = document.querySelector("#scrollContainer");
  container.scrollTo({
    top: height,
    behavior: "auto",
  });
};

// 审核通过
const handleAudit = async (flag) => {
  try {
    const res = await review({
      spuIds: spuId.value,
      reviewType: form.value.dev_status == 2 ? 1 : form.value.dev_status == 3 ? 2 : "",
      reviewOpinion: flag,
      reviewRemark: "",
    });
    if (res.data) {
      ElMessage.success(res.message);
      queryDetail("edit");
    } else {
      ElMessage.error(res.message);
    }
  } catch (e) {
    throw Error(e);
  }
};

const infringementRef = ref();
const handleInfringement = async () => {
  const goods_sku = form.value.goods_sku.map((i) => {
    return {
      custom_sku: i.custom_sku,
      goods_sku_recommended_platform: i.goods_sku_recommended_platform,
    };
  });
  try {
    const res = await infringementDetection({
      goods_sku,
    });
    ElMessage.success("检测无异常");
  } catch (e) {
    throw Error(e);
  }
};

const copySKURef = ref();
const copySKUFun = async (type) => {
  if (form.value.goods_sku.length <= 1) {
    ElMessage.error("暂无可复制SKU信息");
    return;
  }
  copySKURef.value.open(type, activeName.value);
};

const deepCopyWithPreserveId = (source, target, sku) => {
  for (const key in source) {
    if (source.hasOwnProperty(key)) {
      if (typeof source[key] === "object" && source[key] !== null) {
        // 如果属性值是对象且不为 null，递归调用 deepCopyWithPreserveId
        target[key] = deepCopyWithPreserveId(source[key], target[key] || {}, sku);
      } else if (
        key === "id" ||
        key === "sku_id" ||
        key === "custom_sku" ||
        key === "sku_cn_title" ||
        key === "sku_en_title" ||
        key === "sku_code" ||
        key === "main_attribute" ||
        key === "specifications" ||
        key === "title" ||
        key == "color" ||
        key === "size" ||
        (key === "sai_he_sku" && target.hasOwnProperty(key))
      ) {
        // 保留第二个对象内嵌套结构的 id 属性不变
        continue;
      } else {
        // 复制其他属性值
        target[key] = source[key];
        target["sku"] = sku;
      }
    }
  }
  return target;
};

const changeAttribute = (index = 0) => {
  activeName.value = form.value.goods_sku[index]?.sku;
  goods_sku_list.value = form.value.goods_sku;
  // handleResize();
};
const beforeRouteLeave = () => {
  window.removeEventListener("mousemove", handleMouseMove);
};
onBeforeUnmount(async () => {
  clearTimer();
  beforeRouteLeave();
  // if (timerActive.value) return;
  try {
    if (!spuId.value) return;
    const res = await unLock({
      spuId: spuId.value,
    });
    if (res.code != 200) {
      ElMessage.warning(res.message);
    }
  } catch (e) {
    throw Error(e);
  }
});
const routeLeave = ref(false);
onBeforeRouteLeave(() => {
  routeLeave.value = true;
  beforeRouteLeave();
});
onActivated(() => {
  if (isFirstLoad.value) return;
  if (countdown.value <= lockduration && countdown.value > 0) {
    ElMessageBox.confirm(
      "长时间未操作，请尽快保存数据；超过10分钟未操作，将解除编辑锁定",
      "提示",
      {
        confirmButtonText: "确定",
        showClose: false,
        type: "warning",
        confirmButtonClass: "btnFalses",
        showCancelButton: false,
      }
    );
  }
  if (countdown.value == 0) {
    // ElMessageBox.confirm(
    //   "您已五分钟未操作此编辑页面，已经自动解除锁定，数据可能已有其他同事正在操作，请确认，防止数据被覆盖。",
    //   "提示",
    //   {
    //     confirmButtonText: "确定",
    //     showClose: false,
    //     type: "warning",
    //     confirmButtonClass: "btnFalses",
    //     showCancelButton: false,
    //   }
    // ).then(async () => {
    //   unLockSpu();
    // action.setGlobalState({
    //   changeMicoTabsPath: {
    //     type: 'closeActiveTab',
    //   }
    // })
    // });
    // return;
  }
  window.addEventListener("mousemove", handleMouseMove);
});

// const containerSKu = ref();
// const hasOverflow = ref(false);
// const showSku = ref([]);
// const hideSku = ref([]);

const handleResize = () => {
  // let ind = Math.floor((containerSKu.value?.clientWidth - 120) / 260);
  // hasOverflow.value = ind < goods_sku_list.value?.length;
  // // 检查是否存在匹配的特定SKU
  // const specifiedSkuIndex = goods_sku_list.value.findIndex(
  //   (item) => item.custom_sku === sku.value
  // );
  // // 如果存在匹配的特定SKU，则将其移到列表的第一个位置
  // if (specifiedSkuIndex !== -1) {
  //   // 将匹配的SKU移除并插入到列表的第一个位置
  //   // 将匹配的SKU对象从数组中取出并插入到数组的第一个位置
  //   const specifiedSkuObject = goods_sku_list.value.splice(specifiedSkuIndex, 1)[0];
  //   goods_sku_list.value.unshift(specifiedSkuObject);
  // }
  // showSku.value = goods_sku_list.value?.slice(0, ind);
  // hideSku.value = goods_sku_list.value?.slice(ind);
};
const skuLoading = ref(false);
const handleTag = (val) => {
  // skuLoading.value = true;
  // // activeName.value = val;
  // setTimeout(() => {
  //   skuLoading.value = false;
  // }, 1000);
};

// 处理多属性为空的情况
const creatSpecification = (sku_specification) => {
  const { attributes, header } = sku_specification;
  const specification_list = header.map((i) => {
    i.is_relation_img = 0;
    i.group_name = i.name;
    i.loading = false;
    i.show = true;
    i.valueName = "";
    i.values = [
      {
        language_name: "中文",
        language_id: 1,
        language_code: "zh-chs",
        show: true,
        name: i.name,
        language_values: [
          {
            language_id: 1,
            group: 1,
            spu_id: form.value.spu,
            name: i.name,
            value: attributes[i.key],
          },
        ],
      },
    ];
    return i;
  });
  return specification_list;
};

// 是否有新增SKU
const is_add_sku = computed(() => {
  return form.value.goods_sku?.some((item) => !item.id);
});

// SPU信息权限
const permission_spu_info = computed(() => {
  return (
    (window.BTN_AUTH || []).includes("/goods/task/product/spu-info") &&
    !is_add_sku.value &&
    handleType.value == "edit"
  );
});

// 多属性信息权限
const permission_multiattribute_info = computed(() => {
  return (
    (window.BTN_AUTH || []).includes("/goods/task/product/multiattribute-info") &&
    !is_add_sku.value &&
    handleType.value == "edit"
  );
});

// SKU基础信息权限
const permission_sku_info = computed(() => {
  return (
    (window.BTN_AUTH || []).includes("/goods/task/product/basic-info") &&
    !is_add_sku.value &&
    handleType.value == "edit"
  );
});

// SKU处理人信息权限
const permission_people_info = computed(() => {
  return (
    (window.BTN_AUTH || []).includes("/goods/task/product/people-info") &&
    !is_add_sku.value &&
    handleType.value == "edit"
  );
});

// 产品重量尺寸权限
const permission_weight_size = computed(() => {
  return (
    (window.BTN_AUTH || []).includes("/goods/task/product/weight-size-info") &&
    !is_add_sku.value &&
    handleType.value == "edit"
  );
});

// 图片任务权限
const permission_picture = computed(() => {
  return (
    (window.BTN_AUTH || []).includes("/goods/task/product/picture-info") &&
    !is_add_sku.value &&
    handleType.value == "edit"
  );
});

// 备注权限
const permission_remark = computed(() => {
  return (
    (window.BTN_AUTH || []).includes("/goods/task/product/remark-info") &&
    !is_add_sku.value &&
    handleType.value == "edit"
  );
});

// 证书权限
const permission_certificate = computed(() => {
  return (
    (window.BTN_AUTH || []).includes("/goods/task/product/certificate-info") &&
    !is_add_sku.value &&
    handleType.value == "edit"
  );
});

// 推荐平台权限
const permission_platform = computed(() => {
  return (
    (window.BTN_AUTH || []).includes("/goods/task/product/platform-site-info") &&
    !is_add_sku.value &&
    handleType.value == "edit"
  );
});

// 供应商权限
const permission_general = computed(() => {
  return (
    (window.BTN_AUTH || []).includes("/goods/task/product/general-info") &&
    !is_add_sku.value &&
    handleType.value == "edit"
  );
});

// 商品描述权限
const permission_product_description = computed(() => {
  return (
    (window.BTN_AUTH || []).includes("/goods/task/product/product-description") &&
    !is_add_sku.value &&
    handleType.value == "edit"
  );
});

// 关联辅料权限
const permission_ingredient_info = computed(() => {
  return (
    (window.BTN_AUTH || []).includes("/goods/task/product/ingredient-info") &&
    !is_add_sku.value &&
    handleType.value == "edit"
  );
});

// 组合SKU权限
const permission_combination_sku = computed(() => {
  return (
    (window.BTN_AUTH || []).includes("/goods/task/product/combination-SKU") &&
    !is_add_sku.value &&
    handleType.value == "edit"
  );
});

const permission_all = computed(() => {
  const requiredPermissions = [
    "/goods/task/product/spu-info",
    "/goods/task/product/people-info",
    "/goods/task/product/basic-info",
    "/goods/task/product/multiattribute-info",
    "/goods/task/product/remark-info",
    "/goods/task/product/weight-size-info",
    "/goods/task/product/picture-info",
    "/goods/task/product/general-info",
    "/goods/task/product/certificate-info",
    "/goods/task/product/platform-site-info",
    "/goods/task/product/product-description",
    "/goods/task/product/ingredient-info",
    "/goods/task/product/combination-SKU",
  ];

  return !requiredPermissions.every((permission) =>
    (window.BTN_AUTH || []).includes(permission)
  );
});

// 检测SKU辅料
const checkSKUAccessories = async (sku_ids) => {
  if (sku_ids?.length == 0) {
    return false;
  }
  try {
    const res = await getSKUDetails({
      id: sku_ids,
    });
    for (let i = 0; i < res.data.length; i++) {
      const { length, width, height } = res.data[i]?.packing_size_cm;
      const dimensions = [length, width, height].sort((a, b) => a - b);
      if (dimensions[0] > 0 && dimensions[1] >= 10 && dimensions[2] >= 15) {
        return true;
      }
    }
    return false;
  } catch (error) {
    console.error("Error fetching SKU details:", error); // 处理可能的错误
    return false;
  }
};

// 获取头程费用设置
const base_head_freight_list = ref([]);
const getBaseHeadFreightList = async () => {
  try {
    const res = await queryBaseHeadFreightList({
      pageSize: 100,
    });

    base_head_freight_list.value = res.data.map((item) => {
      const newId = item.id;
      item.base_head_freight_id = newId;
      delete item.id;
      return item;
    });
  } catch (e) {
    throw Error(e);
  }
};

provide("base_head_freight_list", base_head_freight_list);

const exchange_rate = ref("");
const getExchangeRate = async () => {
  try {
    const res = await getCurrency({
      currency: "USD",
    });
    exchange_rate.value = res.data[0]?.exchange_rate;
  } catch (e) {
    throw Error(e);
  }
};

// 同步SPU 名称到SKU
const syncName = () => {
  multiAttributeRef.value.inputFocus();
};

const changeProductIdentification = (val, row) => {
  return product_identification_image.get(val);
};

const changeTagStyle = (val, row) => {
  return tag_style_image.get(val);
};

const handleRegionSave = async (edit_type, item, title) => {
  console.log(title);
  await handletTwiceConfirm(
    title ||
      `是否保存${regionNameMap.get(
        edit_type
      )}区域信息，点击确认则对该区域字段执行保存，并刷新当前编辑页面，请知悉。`
  );
  const data = {
    spu_id: form.value.id,
    sku_id: item?.id || "",
    edit_type,
  };
  let info = null;
  switch (edit_type) {
    case "goods_spu":
      info = {
        spu_cn_title: form.value.spu_cn_title,
        need_photo: form.value.need_photo,
        need_processing: form.value.need_processing,
        spu_unit: form.value.spu_unit,
        specification_model: form.value.specification_model,
        goods_source: form.value.goods_source,
        logistics_attributes: form.value.logistics_attributes,
        logistics_attributes_name: form.value.logistics_attributes_name,
        brand_type: form.value.brand_type,
        imitation_remark: form.value.imitation_remark,
        warehouse_id: form.value.warehouse_id,
        warehouse_name: form.value.warehouse_name,
        recommended_level: form.value.recommended_level,
      };
      break;
    case "goods_sku_attr":
      info = {
        goods_sku: {
          id: item.id,
          sku_cn_title: item.sku_cn_title,
          sku_en_title: item.sku_en_title,
          sku_specification: item.sku_specification,
          goods_sku_title: item.goods_sku_title,
          custom_sku: item.custom_sku,
        },
      };
      break;
    case "goods_sku_info":
      const new_goods_sku_sell_month = deepClone(item.goods_sku_sell_month);
      const goods_sku_sell_month = new_goods_sku_sell_month.filter((i) => {
        return !(
          Array.isArray(i.country) &&
          i.country.length === 0 &&
          !i.hot_sell_start_month &&
          !i.hot_sell_end_month
        );
      });
      info = {
        spu_sales_status: form.value.spu_sales_status,
        spu_supply_status: form.value.spu_supply_status,
        spu_clean_product_status: form.value.spu_clean_product_status,
        spu_status: form.value.spu_status,
        goods_sku: {
          id: item.id,
          product_status: item.product_status,
          sales_status: item.sales_status,
          supply_status: item.supply_status,
          goods_sku_sales_info: item.goods_sku_sales_info,
          sku_product_type: item.sku_product_type,
          accessories_use: item.accessories_use,
          is_transparent_plan: item.is_transparent_plan,
          sample_purchase_type: item.sample_purchase_type,
          item_number: item.item_number,
          clean_product_status: item.clean_product_status,
          product_level: item.product_level,
          goods_sku_authentication:
            item.goods_sku_authentication &&
            item.goods_sku_authentication.filter((j) => {
              if (j.country.length > 0 && j.authentication_name) {
                return j;
              }
              if (j.id && j.country.length == 0 && !j.authentication_name) {
                j.delete = 1;
                return j;
              }
            }),
          goods_sku_prohibited_sales:
            item.goods_sku_prohibited_sales &&
            item.goods_sku_prohibited_sales.filter((j) => {
              if (j.platform_id && j.site_code) {
                return j;
              }
            }),
          goods_sku_sell_month: goods_sku_sell_month,
          goods_sku_relation_old: item.goods_sku_relation_old,
        },
      };
      break;
    case "goods_sku_user":
      info = {
        goods_sku: {
          id: item.id,
          developer_id: item.developer_id,
          purchaser_id: item.purchaser_id,
          quality_inspector_id: item.quality_inspector_id,
          img_processor_id: item.img_processor_id,
          editor_id: item.editor_id,
          product_manage_id: item.product_manage_id,
        },
      };
      break;
    case "goods_sku_weight":
      if (!item?.gross_weight_g || !item?.net_weight_g) {
        ElMessage.warning("产品毛重和净重不能为空!");
        return;
      }
      if (
        classified_overseas_position.includes(
          form.value.spu_category ? form.value.spu_category[0] : ""
        )
      ) {
        const { length, width, height } = item.packing_size_cm;
        const dimensions = [length, width, height].sort((a, b) => a - b);
        if (!(dimensions[0] > 0 && dimensions[1] >= 10 && dimensions[2] >= 15)) {
          const sku_ids = item.goods_sku_accessories
            .filter((i) => !i.delete)
            .map((i) => i.accessory_sku_id);
          const is_satisfy = await checkSKUAccessories(sku_ids);
          if (!is_satisfy) {
            ElMessage.warning(
              "海外仓SKU的包装尺寸或者绑定的辅料包装尺寸，至少有一边>=10cm;一边>=15cm且必须>0，当前SKU未满足，请核实；若有疑问可咨询物流部"
            );
            return;
          }
        }
      }
      info = {
        goods_sku: {
          id: item.id,
          gross_weight_g: item.gross_weight_g,
          net_weight_g: item.net_weight_g,
          packing_weight_g: item.packing_weight_g,
          packing_size_cm: item.packing_size_cm,
          product_size_cm: item.product_size_cm,
          packing_qty_size_cm: item.packing_qty_size_cm,
          packing_gross_weight_kg: item.packing_gross_weight_kg,
          cabinets_qty: item.cabinets_qty,
          packing_qty: item.packing_qty,
        },
      };
      break;
    case "goods_sku_image":
      const sku_gallery = deepClone(item.goods_sku_gallery);
      const goods_sku_gallery = sku_gallery.map((i) => {
        i.contents = i.contents
          .filter((j) => j.values.length > 0)
          .map((k) => {
            k.values = k.values.map((v, w) => {
              v.sort = w;
              return v;
            });
            return k;
          });
        return i;
      });
      info = {
        goods_sku: {
          id: item.id,
          goods_sku_gallery,
          attr_img: item.attr_img,
        },
      };
      break;
    case "goods_sku_remark":
      info = {
        goods_sku: {
          id: item.id,
          goods_sku_remark: item.goods_sku_remark,
        },
      };
      break;
    case "goods_sku_certificate":
      info = {
        goods_sku: {
          id: item.id,
          goods_sku_certificate: item.goods_sku_certificate,
        },
      };
      break;
    case "goods_sku_recommended_platform":
      info = {
        goods_sku: {
          id: item.id,
          goods_sku_recommended_platform: item.goods_sku_recommended_platform,
        },
      };
      break;
    case "goods_sku_description":
      info = {
        goods_sku: {
          id: item.id,
          goods_sku_description: item.goods_sku_description,
        },
      };
      break;
    case "goods_sku_combination_sku":
      info = {
        goods_sku: {
          id: item.id,
          goods_sku_combination_sku: item.goods_sku_combination_sku,
        },
      };
      break;
    case "goods_sku_accessories":
      info = {
        goods_sku: {
          id: item.id,
          goods_sku_accessories: item.goods_sku_accessories,
        },
      };
      break;
    case "goods_sku_relation":
      info = {
        goods_sku: {
          id: item.id,
          goods_sku_relation: item.goods_sku_relation,
        },
      };
      break;

    default:
      break;
  }

  regionSave({ ...data, ...info });
};

const regionSave = async (data) => {
  try {
    const res = await goodsRegionSave(data);
    ElMessage.success("保存成功");
    queryDetail("edit");
  } catch (e) {
    throw Error(e);
  }
};

const changeGeneralactive = () => {
  if (generalactive.value == "9") {
    generalactive.value = "Supplier";
  }
};
</script>

<style lang="scss" scoped>
@import "../index.scss";
</style>
